package com.mhr.ai.cr.service

import com.google.gson.Gson
import com.google.gson.JsonObject
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.util.concurrent.TimeUnit

/**
 * HTTP 客户端服务
 * 负责处理与 Git 平台的 API 通信
 */
@Service(Service.Level.APP)
class HttpClientService {
    
    private val logger = thisLogger()
    private val gson = Gson()
    
    private val httpClient = OkHttpClient.Builder()
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .build()
    
    /**
     * 发送 GET 请求并返回 JSON 对象
     */
    suspend fun getJson(url: String, headers: Map<String, String> = emptyMap()): Result<JsonObject> = 
        withContext(Dispatchers.IO) {
            try {
                logger.info("发送 GET 请求: $url")
                
                val requestBuilder = Request.Builder().url(url)
                
                // 添加默认请求头
                requestBuilder.addHeader("User-Agent", "AI-Git-Code-Review-Plugin/1.0")
                requestBuilder.addHeader("Accept", "application/json")
                
                // 添加自定义请求头
                headers.forEach { (key, value) ->
                    requestBuilder.addHeader(key, value)
                }
                
                val request = requestBuilder.build()
                
                httpClient.newCall(request).execute().use { response ->
                    if (!response.isSuccessful) {
                        return@withContext Result.failure(
                            RuntimeException("HTTP 请求失败，状态码: ${response.code}, 消息: ${response.message}")
                        )
                    }
                    
                    val responseBody = response.body?.string()
                        ?: return@withContext Result.failure(RuntimeException("响应体为空"))
                    
                    val jsonObject = gson.fromJson(responseBody, JsonObject::class.java)
                    Result.success(jsonObject)
                }
            } catch (e: Exception) {
                logger.error("HTTP 请求失败", e)
                Result.failure(e)
            }
        }
    
    /**
     * 发送 GET 请求并返回字符串
     */
    suspend fun getString(url: String, headers: Map<String, String> = emptyMap()): Result<String> = 
        withContext(Dispatchers.IO) {
            try {
                logger.info("发送 GET 请求: $url")
                
                val requestBuilder = Request.Builder().url(url)
                
                // 添加默认请求头
                requestBuilder.addHeader("User-Agent", "AI-Git-Code-Review-Plugin/1.0")
                
                // 添加自定义请求头
                headers.forEach { (key, value) ->
                    requestBuilder.addHeader(key, value)
                }
                
                val request = requestBuilder.build()
                
                httpClient.newCall(request).execute().use { response ->
                    if (!response.isSuccessful) {
                        return@withContext Result.failure(
                            RuntimeException("HTTP 请求失败，状态码: ${response.code}, 消息: ${response.message}")
                        )
                    }
                    
                    val responseBody = response.body?.string()
                        ?: return@withContext Result.failure(RuntimeException("响应体为空"))
                    
                    Result.success(responseBody)
                }
            } catch (e: Exception) {
                logger.error("HTTP 请求失败", e)
                Result.failure(e)
            }
        }
}